package com.cqjtu.tto.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqjtu.tto.dao.mapper.SysUserMapper;
import com.cqjtu.tto.dao.pojo.SysUser;
import com.cqjtu.tto.service.LoginService;
import com.cqjtu.tto.utils.UserPasswordUtils;
import com.cqjtu.tto.vo.ErrorCode;
import com.cqjtu.tto.vo.Results;
import com.cqjtu.tto.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author：monkey-L
 * @description:
 * @date: 18:02 2021/12/10
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Override
    public Results login(LoginParam loginParam) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserLambdaQueryWrapper.eq(SysUser::getUserName,loginParam.getUserName());
        sysUserLambdaQueryWrapper.last("limit 1");
        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper);
//        System.out.println("1111111");
//        System.out.println(sysUser);
        if (sysUser != null) {
            String password = DigestUtils.md5Hex(loginParam.getUserPassword() + UserPasswordUtils.slat);
            if (!sysUser.getUserPassword().equals(password)) {
//                System.out.println("222222");
                System.out.println(loginParam.getUserPassword());
                return Results.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            }
            //将用户名存到session中
//            httpSession.setAttribute ("username", loginParam.getUserName());
            StpUtil.setLoginId (sysUser.getUserName ());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo ();
            Map map = new HashMap();
            map.put ("user", sysUser);
            map.put ("tokenInfo", tokenInfo);
            return Results.success(map);
        }
        return Results.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
    }
}
